<?php

namespace app\api\controller;



use app\admin\model\Order;
use app\api\service\OrderService;
use app\common\controller\Api;
use think\Db;

class Notify extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 微信支付回调
     */
    public function pay()
    {

        $xml = file_get_contents('php://input');
        $message= simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $message = json_encode($message);
        $message= json_decode($message, true);
               $log= db::name('pay_log')->insert([
                    'open_id' => $message['openid'],
                    'mch_id' => $message['mch_id'],
                    'out_trade_no' => $message['out_trade_no'],
                    'pay_money' => $message['total_fee'] / 100,
                    'transaction_id' => $message['transaction_id'],
                    'app_id' => $message['appid'],
                    'status' => 1,
                    'pay_time' => time(),
                    'response' => json_encode($message),
                ]);
            try {
                if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                    // 用户是否支付成功
                    if ($message['result_code'] === 'SUCCESS') {
                        // 统一处理订单回调
                        $order = Order::where('order_no', '=', $message['out_trade_no'])->find();

                        $result = Order::where('id', '=', $order['id'])->where(['order_status' => 0, 'pay_status' => 0])->update(['pay_status' => 1, 'pay_time' => time(), 'order_status' => 1]);
                        if($order['goodtype']==1){
                            $OrderService=new OrderService();
                            $OrderService->fenyong($order['id']);
                        }
                              if ($result !== false) {
                            exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
                        } else {
                            exit('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>');
                        }
                    } else {
                        exit('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>');
                    }
                } else {
                    exit('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>');
                }
            } catch (\think\exception\HttpResponseException $ex) {
                $data = $ex->getResponse()->getData();
                $this->handleError($log, $data['msg'] ?? $ex->getMessage());
            } catch (\Exception $ex) {
                $this->handleError($log, $ex->getMessage());
            }
            return true;
    }


    public function  ceshi(){

    }

}
